using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Linq;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;


public partial class MapWithAutoMovingPushpins : System.Web.UI.Page
{

    #region MapWithAutoMovingPushpinsDataTableCache
    private DataTable MapWithAutoMovingPushpinsDataTableCache
    {
        get
        {
            DataTable objTable = null;
            if (Cache["MapWithAutoMovingPushpins.aspx" + Session.SessionID] != null)
                objTable = (DataTable)Cache["MapWithAutoMovingPushpins.aspx" + Session.SessionID];
            return objTable;
        }
        set
        {
            if (value != null)
            {
                Cache.Insert("MapWithAutoMovingPushpins.aspx" + Session.SessionID, value, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
            }
        }
    }



    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        string algo = ASPxGridView1.SettingsPager.Position.ToString();
        if (Timer1.Enabled)
        {
            btnControlTimer.Text = "Detener";
        }
        else
        {
            btnControlTimer.Text = "Inciar";
        }
        if (!IsPostBack)
        {

            crearTabla();
            Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);


            //You must specify Google Map API Key for this component. You can obtain this key from http://code.google.com/apis/maps/signup.html
            //For samples to run properly, set GoogleAPIKey in Web.Config file.
            GoogleMapForASPNet1.GoogleMapObject.APIKey = ConfigurationManager.AppSettings["GoogleAPIKey"];

            //Specify width and height for map. You can specify either in pixels or in percentage relative to it's container.
            GoogleMapForASPNet1.GoogleMapObject.Width = "800px"; // You can also specify percentage(e.g. 80%) here
            GoogleMapForASPNet1.GoogleMapObject.Height = "600px";

            //Specify initial Zoom level.
            GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 8;

            //Specify Center Point for map. Map will be centered on this point.
            GoogleMapForASPNet1.GoogleMapObject.CenterPoint = new GooglePoint("1", 3.78321671, -76.6397629);

            WebServiceRastrack.wsGetGPSDataReportsSoapClient obj = new WebServiceRastrack.wsGetGPSDataReportsSoapClient();


            var datos = from a in contexto.PAS_CONSULTAR_VEHICULOS_UBICACION_MAPA()
                        select a;
            foreach (var v in datos)
            {
                //if (v.AMA_PLACA == "SQA770")
                //if (v.AMA_PLACA != "SQA771" && v.AMA_PLACA != "SQA774" && v.AMA_PLACA != "SOA196" && v.AMA_PLACA != "SQA772" && v.AMA_PLACA != "SOA433" && v.AMA_PLACA != "SON549" && v.AMA_PLACA != "SQA776" && v.AMA_PLACA != "SQA766" && v.AMA_PLACA != "TAL620" && v.AMA_PLACA != "SQB440" && v.AMA_PLACA != "SOA429" && v.AMA_PLACA != "SOA440")
                //{
                WebServiceRastrack.cDataLastReportVehicle objDataPlaca = null ;
                try
                {
                    objDataPlaca = obj.wmGetGPSDataReport(v.AMA_PLACA);
                }
                catch (Exception ex)
                {

                    ex.Message.ToString();
                }
               


                GooglePoint GP1 = new GooglePoint();
                if (objDataPlaca != null)
                if (objDataPlaca.p_fLatitude != 0)
                {
                    GP1.ID = v.AMA_PLACA;
                    GP1.Latitude = objDataPlaca.p_fLatitude;
                    string strDireccion = objDataPlaca.p_sAddress;

                    GP1.Longitude = objDataPlaca.p_fLongitude;
                    //Consulta los vines relacionados y trailer relacionado con ese cabezote
                    //var datosOrden = from a in contexto.AUT_ORDEN_SALIDAs
                    //                 // join b in contexto.AUT_CLIENTEs on a.ACL_ID_ORIGEN equals b.ACL_ID
                    //                 // join c in contexto.AUT_CLIENTEs on a.ACL_ID_DESTINO equals c.ACL_ID
                    //                 join d in contexto.AUT_VEHICULOs on a.AVE_ID_CABEZOTE equals d.AVE_ID
                    //                 join r in contexto.AUT_VEHICULOs on a.AVE_ID_TRAILER equals r.AVE_ID
                    //                 join f in contexto.AUT_ESTADOS_ORDEN_SALIDAs on a.AES_ID equals f.AES_ID
                    //                 join p in contexto.AUT_PERSONALs on a.APE_ID equals p.APE_ID
                    //                 where
                    //                       d.AMA_PLACA == v.AMA_PLACA && f.AES_ID == 7
                    //                 //    e.TEA_AREA_ID == Convert.ToInt32(ConfigurationManager.AppSettings["AREA_ID"].ToString())
                    //                 select new
                    //                 {
                    //                     a.AOS_ID,
                    //                     CABEZOTE = d.AMA_PLACA,
                    //                     TRAILER = r.AMA_PLACA,
                    //                     //a.AOS_FECHA_SOLICITUD,
                    //                     //a.AOS_FECHA_ASIGNACION,
                    //                     //a.AOS_FECHA_ENTREGA,
                    //                     AOS_ESTADO = f.AES_NOMBRE,
                    //                     CONDUCTOR = p.APE_NOMBRE
                    //                 };
                    // string strVines = "";
                    bool boolBandera = false;
                    //foreach (var z in datosOrden)
                    //{
                    //vines asociados a la orden

                    //var datosVinLeberar = from a in contexto.AUT_ORDEN_SALIDA_AUT_VINs
                    //                      where a.AOS_ID == z.AOS_ID
                    //                      select a;

                    //foreach (var j in datosVinLeberar)
                    //{


                    string strAdministradores = ConfigurationManager.AppSettings["perfilAdministrador"].ToString();
                    string[] strArregloAdministradores = strAdministradores.Split(',');
                    //foreach (string var in strArregloAdministradores)
                    //{
                    //    if (!String.IsNullOrEmpty(Session["PerfilActual"].ToString()))
                    //    {
                    //        if (Session["PerfilActual"].ToString() == var)
                    //        {
                    //            boolBandera = true;
                    //            break;
                    //        }
                    //    }


                    //}

                    //if (boolBandera)
                    //{
                    //    var datosVin = from f in contexto.AUT_VINEs
                    //                   where f.AVI_ID == j.AVI_ID && f.AES_ID == 1
                    //                   select f;
                    //    //CONSULTA LOS VINES ASOCIADOS A LA ORDEN
                    //    foreach (var o in datosVin)
                    //    {
                    //        // SI EL ESTADO DEL VIN SE ENCUENTRA EN TRANSITO LO MUESTRA
                    //        //if (o.AES_ID == 1)
                    //        //{
                    //        if (strVines == "")
                    //            strVines = o.AVI_VIN;
                    //        else
                    //            strVines = strVines + ", " + o.AVI_VIN + " " + o.AVI_CLIENTE;

                    //    }
                    //}
                    //else
                    //{
                    //    if (!String.IsNullOrEmpty(Session["Login"].ToString()))
                    //    {
                    //        var datosVin = from f in contexto.AUT_VINEs
                    //                       where f.AVI_ID == j.AVI_ID && f.AES_ID == 1 && f.AVI_CLIENTE.ToString().ToLower() == Session["Login"].ToString().ToLower()
                    //                       select f;
                    //        //CONSULTA LOS VINES ASOCIADOS A LA ORDEN
                    //        foreach (var o in datosVin)
                    //        {
                    //            if (strVines == "")
                    //                strVines = o.AVI_VIN;
                    //            else
                    //                strVines = strVines + ", " + o.AVI_VIN + " " + o.AVI_CLIENTE;
                    //        }
                    //    }
                    //}

                    //}

                    if (v.VINES != "")
                    {
                        GP1.InfoHTML = "<table><tr><td>PLACA : </td><td>" + v.AMA_PLACA + "</td></tr><tr><td>TRAILER : </td><td>" + v.TRAILER + "</td></tr><tr><td>CONDUCTOR : </td><td>" + v.CONDUCTOR + "</td></tr>" + "</tr><tr><td>DIRECCION : </td><td>" + strDireccion + "</td></tr>" + "</tr><tr><td>VINES : </td><td>" + v.VINES + "</td></tr>" + "</table>";
                        //GP1.IconImage = "icons/SchoolBus.png";
                        GP1.IconImage = "https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=ski|bb|" + v.AMA_PLACA + "|E4F70A|000000";
                        if (objDataPlaca.p_fLatitude != 0)
                        {

                            DataRow row = ds.Tables[0].NewRow();
                            row["PLACA"] = v.AMA_PLACA;
                            row["DIRECCION"] = strDireccion;
                            row["TRAILER"] = v.TRAILER;

                            row["CONDUCTOR"] = v.CONDUCTOR;

                            row["VINES"] = v.VINES;

                            //row["AOS_ID"] = v.AOS_ID;
                            ds.Tables[0].Rows.Add(row);

                            ASPxGridView1.DataSource = ds.Tables[0];
                            ASPxGridView1.DataBind();
                            MapWithAutoMovingPushpinsDataTableCache = GetDataView(ASPxGridView1);
                        }
                    }
                    //}
                    if (GP1.InfoHTML == "")
                    {
                        GP1.InfoHTML = "<table><tr><td>PLACA : </td><td>" + v.AMA_PLACA + "</td></tr><tr><td>SIN CARGA</td><td></td></tr></table>";

                        GP1.IconImage = "https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=ski|bb|" + v.AMA_PLACA + "|FFFFFF|000000";
                    }

                    if (v.VINES == "" && boolBandera)
                        GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
                    else if (v.VINES != "" && !boolBandera)
                        GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
                    else if (v.VINES != "" && boolBandera)
                        GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
                }
                //}


            }


        }
        else
        {


            if (MapWithAutoMovingPushpinsDataTableCache != null)
            {
                ASPxGridView1.DataSource = MapWithAutoMovingPushpinsDataTableCache;
                ASPxGridView1.DataBind();
            }
        }

    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {


        Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);
        WebServiceRastrack.wsGetGPSDataReportsSoapClient obj = new WebServiceRastrack.wsGetGPSDataReportsSoapClient();
        
                    var datos = from a in contexto.PAS_CONSULTAR_VEHICULOS_UBICACION_MAPA()

                    
                    select a;
        crearTabla();
        foreach (var v in datos)
        {
            //if (v.AMA_PLACA == "SQA770")
            //if (v.AMA_PLACA != "SQA771" && v.AMA_PLACA != "SQA774" && v.AMA_PLACA != "SOA196" && v.AMA_PLACA != "SQA772" && v.AMA_PLACA != "SOA433" && v.AMA_PLACA != "SON549" && v.AMA_PLACA != "SQA776" && v.AMA_PLACA != "SQA766" && v.AMA_PLACA != "TAL620" && v.AMA_PLACA != "SQB440" && v.AMA_PLACA != "SOA429" && v.AMA_PLACA != "SOA440")
            //{
            WebServiceRastrack.cDataLastReportVehicle objDataPlaca = null;
            try
            {
                objDataPlaca = obj.wmGetGPSDataReport(v.AMA_PLACA);
            }
            catch (Exception ex)
            {

                ex.Message.ToString();
            }

            GooglePoint GP1 = new GooglePoint();
            if (objDataPlaca != null)
            if (objDataPlaca.p_fLatitude != 0)
            {
                GP1.ID = v.AMA_PLACA;
                GP1.Latitude = objDataPlaca.p_fLatitude;
                string strDireccion = objDataPlaca.p_sAddress;

                GP1.Longitude = objDataPlaca.p_fLongitude;
                //Consulta los vines relacionados y trailer relacionado con ese cabezote
                //var datosOrden = from a in contexto.AUT_ORDEN_SALIDAs
                //                 // join b in contexto.AUT_CLIENTEs on a.ACL_ID_ORIGEN equals b.ACL_ID
                //                 // join c in contexto.AUT_CLIENTEs on a.ACL_ID_DESTINO equals c.ACL_ID
                //                 join d in contexto.AUT_VEHICULOs on a.AVE_ID_CABEZOTE equals d.AVE_ID
                //                 join r in contexto.AUT_VEHICULOs on a.AVE_ID_TRAILER equals r.AVE_ID
                //                 join f in contexto.AUT_ESTADOS_ORDEN_SALIDAs on a.AES_ID equals f.AES_ID
                //                 join p in contexto.AUT_PERSONALs on a.APE_ID equals p.APE_ID
                //                 where
                //                       d.AMA_PLACA == v.AMA_PLACA && f.AES_ID == 7 
                //                 //    e.TEA_AREA_ID == Convert.ToInt32(ConfigurationManager.AppSettings["AREA_ID"].ToString())
                //                 select new
                //                 {
                //                     a.AOS_ID,
                //                     CABEZOTE = d.AMA_PLACA,
                //                     TRAILER = r.AMA_PLACA,
                //                     //a.AOS_FECHA_SOLICITUD,
                //                     //a.AOS_FECHA_ASIGNACION,
                //                     //a.AOS_FECHA_ENTREGA,
                //                     AOS_ESTADO = f.AES_NOMBRE,
                //                     CONDUCTOR = p.APE_NOMBRE
                //                 };
                //string strVines = "";
                //foreach (var z in datosOrden)
                //{
                    //vines asociados a la orden

                    //var datosVinLeberar = from a in contexto.AUT_ORDEN_SALIDA_AUT_VINs
                    //                      where a.AOS_ID == z.AOS_ID
                    //                      select a;

                    //foreach (var j in datosVinLeberar)
                    //{
                        //bool boolBandera = false;

                        //string strAdministradores = ConfigurationManager.AppSettings["perfilAdministrador"].ToString();
                        //string[] strArregloAdministradores = strAdministradores.Split(',');
                        //foreach (string var in strArregloAdministradores)
                        //{
                        //    if (!String.IsNullOrEmpty(Session["PerfilActual"].ToString()))
                        //    {
                        //        if (Session["PerfilActual"].ToString() == var)
                        //        {
                        //            boolBandera = true;
                        //            break;
                        //        }
                        //    }


                        //}

                        //if (boolBandera)
                        //{
                        //    var datosVin = from f in contexto.AUT_VINEs
                        //                   where f.AVI_ID == j.AVI_ID && f.AES_ID == 1
                        //                   select f;
                        //    //CONSULTA LOS VINES ASOCIADOS A LA ORDEN
                        //    foreach (var o in datosVin)
                        //    {
                        //        // SI EL ESTADO DEL VIN SE ENCUENTRA EN TRANSITO LO MUESTRA
                        //        //if (o.AES_ID == 1)
                        //        //{
                        //        if (strVines == "")
                        //            strVines = o.AVI_VIN;
                        //        else
                        //            strVines = strVines + ", " + o.AVI_VIN + " " + o.AVI_CLIENTE;

                        //    }
                        //}
                        //else
                        //{
                        //    if (!String.IsNullOrEmpty(Session["Login"].ToString()))
                        //    {
                        //        var datosVin = from f in contexto.AUT_VINEs
                        //                       where f.AVI_ID == j.AVI_ID && f.AES_ID == 1 && f.AVI_CLIENTE.ToString().ToLower() == Session["Login"].ToString().ToLower()
                        //                       select f;
                        //        //CONSULTA LOS VINES ASOCIADOS A LA ORDEN
                        //        foreach (var o in datosVin)
                        //        {
                        //            if (strVines == "")
                        //                strVines = o.AVI_VIN;
                        //            else
                        //                strVines = strVines + ", " + o.AVI_VIN + " " + o.AVI_CLIENTE;
                        //        }
                        //    }
                        //}

                    //}

                    if (v.VINES != "")
                    {

                        //WebServiceRastrack.cDataLastReportVehicle objDataPlaca = obj.wmGetGPSDataReport(v.AMA_PLACA);
                        if (objDataPlaca.p_fLatitude != 0)
                        {

                            DataRow row = ds.Tables[0].NewRow();
                            row["PLACA"] = v.AMA_PLACA;
                            row["DIRECCION"] = strDireccion;
                            row["TRAILER"] = v.TRAILER;

                            row["CONDUCTOR"] = v.CONDUCTOR;

                            row["VINES"] = v.VINES;

                            //row["AOS_ID"] = v.AOS_ID;
                            
                            ds.Tables[0].Rows.Add(row);

                            if (GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA] != null && GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA] != null)
                            {
                                GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA].Latitude = objDataPlaca.p_fLatitude;
                                GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA].Longitude = objDataPlaca.p_fLongitude;
                            }
                        }

                        if (GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA] != null && GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA] != null)
                        {
                            GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA].Latitude = objDataPlaca.p_fLatitude;
                            GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA].Longitude = objDataPlaca.p_fLongitude;
                        }


       


                        //GP1.InfoHTML = "<table><tr><td>PLACA : </td><td>" + v.AMA_PLACA + "</td></tr><tr><td>TRAILER : </td><td>" + z.TRAILER + "</td></tr><tr><td>CONDUCTOR : </td><td>" + z.CONDUCTOR + "</td></tr>" + "</tr><tr><td>DIRECCION : </td><td>" + strDireccion + "</td></tr>" + "</tr><tr><td>VINES : </td><td>" + strVines + "</td></tr>" + "</table>";
                        ////GP1.IconImage = "icons/SchoolBus.png";
                        //GP1.IconImage = "https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=ski|bb|" + v.AMA_PLACA + "|E4F70A|000000";

                    }
                //}
                //if (GP1.InfoHTML == "")
                //{
                //    GP1.InfoHTML = "<table><tr><td>PLACA : </td><td>" + v.AMA_PLACA + "</td></tr><tr><td>SIN CARGA</td><td></td></tr></table>";

                //    GP1.IconImage = "https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=ski|bb|" + v.AMA_PLACA + "|FFFFFF|000000";
                //}


                //GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
            }
            //}


        }
        
        
       
          //  if (v.AMA_PLACA == "SQA770")
            //    if (v.AMA_PLACA != "SQA771" && v.AMA_PLACA != "SQA774" && v.AMA_PLACA != "SOA196" && v.AMA_PLACA != "SQA772" && v.AMA_PLACA != "SOA433" && v.AMA_PLACA != "SON549" && v.AMA_PLACA != "SQA776" && v.AMA_PLACA != "SQA766" && v.AMA_PLACA != "TAL620" && v.AMA_PLACA != "SQB440" && v.AMA_PLACA != "SOA429" && v.AMA_PLACA != "SOA440")
                    
            //{
            //    WebServiceRastrack.cDataLastReportVehicle objDataPlaca = obj.wmGetGPSDataReport(v.AMA_PLACA);
            //    if (objDataPlaca.p_fLatitude != 0)
            //    {

            //        DataRow row = ds.Tables[0].NewRow();
            //        row["PLACA"] = v.AMA_PLACA;
            //        row["DIRECCION"] = objDataPlaca.p_sAddress;
            //        //row["AOS_ID"] = v.AOS_ID;
            //        ds.Tables[0].Rows.Add(row);
            //        GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA].Latitude = objDataPlaca.p_fLatitude;
            //        GoogleMapForASPNet1.GoogleMapObject.Points[v.AMA_PLACA].Longitude = objDataPlaca.p_fLongitude;
            //    }
            ////}
       

        ASPxGridView1.DataSource = ds.Tables[0];
        ASPxGridView1.DataBind();
         MapWithAutoMovingPushpinsDataTableCache  = GetDataView(ASPxGridView1);
        //busque en que pagina se encuentra si esta en 1 cambie a  2 
       if (ASPxGridView1.PageIndex == 0)
           ASPxGridView1.PageIndex = 1;
       else if( ASPxGridView1.PageIndex == 1)
           ASPxGridView1.PageIndex = 2;
          else if(ASPxGridView1.PageIndex == 2)
           ASPxGridView1.PageIndex = 0;
        

    }

    #region GetDataView
    private DataTable GetDataView(ASPxGridView grid)
    {
        DataTable dt = new DataTable();
        foreach (GridViewColumn col in grid.VisibleColumns)
        {
            GridViewDataColumn dataColumn = col as GridViewDataColumn;
            if (dataColumn == null) continue;
            dt.Columns.Add(dataColumn.FieldName);
        }
        for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            DataRow row = dt.Rows.Add();
            foreach (DataColumn col in dt.Columns)
                row[col.ColumnName] = grid.GetRowValues(i, col.ColumnName);
        }
        return dt;
    }
    #endregion

    protected void Button1_Click(object sender, EventArgs e)
    {
        //WebServiceRastrack.wsGetGPSDataReportsSoapClient obj = new WebServiceRastrack.wsGetGPSDataReportsSoapClient();
        //WebServiceRastrack.cDataLastReportVehicle objData = obj.wmGetGPSDataReport("SQA770");
        //float ftlLatitud = objData.p_fLatitude;
        //float ftlLongitud = objData.p_fLongitude;
        //Label1.Text = ftlLatitud.ToString() + " : " + ftlLongitud.ToString();

        if (Timer1.Enabled)
        {
            btnControlTimer.Text = "Inciar";
            Timer1.Enabled = false;
        }
        else
        {
            btnControlTimer.Text = "Detener";
            Timer1.Enabled = true;
        }
    }

    

    DataSet ds = null;


    private void crearTabla()
    {
        ds = new DataSet();
        DataTable masterTable = new DataTable();
        masterTable.Columns.Add("PLACA", typeof(String));
        masterTable.Columns.Add("DIRECCION", typeof(String));
        masterTable.Columns.Add("TRAILER", typeof(String));
        masterTable.Columns.Add("CONDUCTOR", typeof(String));
        masterTable.Columns.Add("VINES", typeof(String));
        //masterTable.Columns.Add("subtotal", typeof(float));
        //masterTable.Columns.Add("IDArancel", typeof(int));
        masterTable.PrimaryKey = new DataColumn[] { masterTable.Columns["PLACA"] };

        ds.Tables.AddRange(new DataTable[] { masterTable });
        Session["DataSet"] = ds;
    }

}
